#include <Drivers/block/nand/nand_drv.h>
#include <os/ioapi/libblock/include/Blkdev.h>

#include <am_bl_ex.h>
#include <upgrade_img.h>

extern AMEBootPara boot_parameter;
static unsigned is_system_ready=0;
static unsigned is_system_ready_change=0;
unsigned BootGetSystemReady()
{
	switch(boot_parameter.boot_device)
	{
		case SD_SLOT_1:
		case BOOT_NORMAL:
		case SD_SLOT_2:
		case USB_HOST_SLOT:
			break;
		case NAND_SLOT_1:
		case NAND_SLOT_2:
		case NOR_SLOT_2:
			is_system_ready=1;
			break;

	};
	return is_system_ready;
}
char * GetBootDevice()
{
	switch(boot_parameter.boot_device)
	{
		case SD_SLOT_1:
		case BOOT_NORMAL:
		case SD_SLOT_2:
		case USB_HOST_SLOT:
			if(is_system_ready)
				return (char*)(&boot_parameter.boot_path[0]);
			break;
		case NAND_SLOT_1:
			return "/dev/nandcode1";
		case NAND_SLOT_2:
			return "/dev/nandcode2";
		case NOR_SLOT_2:
			return "/dev/norboot";
	};
	return 0;
}
unsigned GetResourceOffset()
{
	return boot_parameter.res_offset;
}
unsigned BootCheckReadyMount(char * dev,char * mount_point)
{
	static char temp[256];
	static unsigned tag=0;
	int len;
	if(is_system_ready==1)
				return 0;
	switch(boot_parameter.boot_device)
	{
		case SD_SLOT_1:
			if(tag==0&&dev&&(is_system_ready==0)&&!strcmp(dev,"SD")&&boot_parameter.boot_path[0]!=0)
			{
				strcpy(temp,(char*)&boot_parameter.boot_path[0]);
				strcpy((char*)(boot_parameter.boot_path),mount_point);
				strcat((char*)(boot_parameter.boot_path),"/");
				strcat((char*)(boot_parameter.boot_path),temp);
				len=strlen((char*)&boot_parameter.boot_path[0])-1;
				while(boot_parameter.boot_path[len]==0x20&&len>=0)
				{
					boot_parameter.boot_path[len]=0;
					len--;
				}
				
				is_system_ready=1;
				return 1;
			}
			
			if(boot_parameter.boot_path[0]==0||tag==1)
			{
				tag=1;
				strcpy((char *)&boot_parameter.boot_path[0],"/dev/disk/sd");
				int fd=open((char *)&boot_parameter.boot_path[0],O_RDONLY);
				if(fd>-1)
				{
					close(fd);
					is_system_ready=1;
					return 1;
				}
			}
			break;
		case NAND_SLOT_1:
			break;
		case NAND_SLOT_2:
			break;
			
	}
	return 0;
}
unsigned BootCheckUnMount(char * dev,char * mount_point)
{
	if(is_system_ready==0)
				return 0;
	switch(boot_parameter.boot_device)
	{
		case SD_SLOT_1:
			if(dev&&(is_system_ready==1)&&!strcmp(dev,"SD"))
			{
				return !strncmp(mount_point,(char *)&boot_parameter.boot_path[0],strlen(mount_point));
				
			}
			if(is_system_ready)
			{
				int fd=open((char *)&boot_parameter.boot_path[0],O_RDONLY);
				if(fd>-1)
				{
					close(fd);
					return 0;
					
				}
				return 1;
			}
			break;
		case NAND_SLOT_1:
			break;
		case NAND_SLOT_2:
			break;
			
	}
	return 0;
}
